# encoding: utf-8
from flask import Flask, session, redirect, url_for, request, render_template, flash
from flask_bootstrap import Bootstrap
from datetime import datetime
from sqlalchemy import or_, and_
from .. import db
from ..models import User,ToDoList
from . import todolist


#在每个请求前检查是否登录，没有登录也跳转到登录页面
@todolist.before_request
def is_login():
     if not 'username' in session:
        return redirect(url_for("user.login"))

## 首页
@todolist.route('/')
def index():
    try:
        records = ToDoList.query.filter_by(author=session['username'])
        all_num = 0
        finished_num = 0
        unfinished_num = 0
        outdate_num = 0

        if records:
        ## 查询各个状态的统计数字并在首页最上面显示
            all_num = records.count()
            finished_num = records.filter(ToDoList.complete == 1).count()
            unfinished_num = records.filter(and_(
                                                    ToDoList.complete == 0,
                                                    ToDoList.expire_time > datetime.now()
                                                    )
                                            ).count()
            outdate_num  = records.filter(and_(
                                                ToDoList.complete == 0,
                                                ToDoList.expire_time < datetime.now()
                                                )
                                            ).count()
        ## 根据在输入框中输入关键字进行查询并返回相应结果，使用like进行匹配
        if request.args.get('query') and records:
            query = request.args.get('query')
            records = records.filter(or_(
                                        ToDoList.task.like('%{}%'.format(query)),
                                        ToDoList.description.like('%{}%'.format(query))
                                        )
                                    )
        ## 根据状态返回相应结果
        if request.args.get('status') and records:
            status = request.args.get('status')
            if status == 'finished':
                records = records.filter(ToDoList.complete == 1)
            elif status == 'unfinished':
                records = records.filter( and_(
                                                ToDoList.complete == 0,
                                                ToDoList.expire_time > datetime.now()
                                                )
                                        )
            elif status == 'outdated':
                records = records.filter(and_(
                                            ToDoList.complete == 0,
                                            ToDoList.expire_time < datetime.now()
                                            )
                                        )
        return render_template('index.html', results = records, all_num=all_num, finished_num=finished_num, unfinished_num=unfinished_num, outdate_num=outdate_num)
    except Exception as e:
        print(e)
        flash('有异常发生，请稍后再试!','danger')
        return render_template('index.html', results = [])

# @todolist.route('/todolist/detail/<id>')
# def detail(id):
#     try:
#         todolist = ToDoList.query.get_or_404(id)
#         db.session.commit()
#         return render_template('todolistdetail.html', result = todolist)
#     except Exception as e:
#         print(e)
#         flash('Error occurred, pls retry it later')
#         return render_template('index.html', results = [])

#添加新的任务
@todolist.route('/todolist/add', methods=['GET','POST'])
def add():
    if request.method == 'POST':
        try: 
            task = request.form['task']
            description = request.form['description']
            category = request.form['category']
            expire_time = request.form['expire_time'] or None
            print(expire_time)
            expire_time = datetime.strptime(expire_time, '%Y-%m-%d') 

            todolist = ToDoList.query.filter_by(task=task).first()
            if todolist:
                flash('计划 {} 已存在！'.format(task),'danger')
                return redirect(url_for('todolist.index'))
            else:
                todolist = ToDoList(task=task,
                            description=description,
                            category=category,
                            author=session['username'],
                            expire_time=expire_time
                            # expire_time = datetime.now()
                            )
                db.session.add(todolist)
                db.session.commit()
                flash('计划创建成功!','success')
                return redirect(url_for('todolist.index'))
        except Exception as e:
            print('exception - {}'.format(str(e)))
            flash('有异常发生，请稍后再试!','danger')
            return redirect(url_for('todolist.index'))
    else:
        return render_template('todolist.html', url="/todolist/add", result=[])

# 根据id删除相应的任务
@todolist.route('/todolist/delete/<id>', methods=['GET','POST'])
def delete(id):
    try:
        todolist = ToDoList.query.get_or_404(id)
        db.session.delete(todolist)
        db.session.commit()
        flash('计划删除成功!','success')
        return redirect(url_for('todolist.index'))
    except Exception as e:
        print('exception - {}'.format(str(e)))
        flash('有异常发生，请稍后再试!','danger')
        return redirect(url_for('todolist.index'))

# 根据id更新相应的任务并保存到数据库
@todolist.route('/todolist/edit/<id>', methods=['GET','POST'])
def edit(id):
    todolist = ToDoList.query.get_or_404(id)
    if request.method == 'POST':
        try: 
            task = request.form['task']
            description = request.form['description']
            category = request.form['category']
            expire_time = request.form['expire_time']
            expire_time = datetime.strptime(expire_time, '%Y-%m-%d') 
            # complete = 0 if request.form['complete'].lower() == 'false' else 1
            complete = int(request.form['complete'])

            todolist.task = task
            todolist.description = description
            todolist.category = category
            todolist.expire_time = expire_time
            todolist.complete = complete
            db.session.commit()

            flash('计划更改成功!','success')
            return redirect(url_for('todolist.index'))
        except Exception as e:
            print('exception - {}'.format(str(e)))
            flash('有异常发生，请稍后再试','danger')
            return redirect(url_for('todolist.index'))
    else:
        return render_template('todolistedit.html', result=todolist)

## 关于页面
@todolist.route('/todolist/about')
def about():
    return render_template('about.html')